from app.models.system import Role, Users, UserRole
from sqlalchemy.orm import Session
from app.conf import settings
from app.utils.security import get_password_hash
from app.utils.utils import getSha256

create_role_list = settings.DEFAULT_ROLE
create_user_list = settings.DEFAULT_USER


def init_db_data(db: Session) -> None:

    admin_id = None
    for role in create_role_list:
        role_name = role.get('name')
        instance = db.query(Role).filter(Role.name == role_name, Role.is_delete == 0).first()  # type: ignore
        if instance:
            if instance.admin:
                admin_id = instance.id
        else:
            db_obj = Role(**role)  # type: ignore
            db.add(db_obj)
            db.commit()
            db.refresh(db_obj)
            if role_name == "管理员":
                admin_id = db_obj.id

    for user in create_user_list:

        is_admin = user.pop("admin", 0)
        username = user.get('username')
        instance = db.query(Users).filter(Users.username == username, Users.is_delete == 0).first()  # type: ignore
        if not instance:
            password = user.pop("password", "password")
            sha_pwd = getSha256(password)
            user['hashed_password'] = get_password_hash(sha_pwd)
            db_obj = Users(**user)  # type: ignore
            db.add(db_obj)
            db.commit()
            db.refresh(db_obj)
            if is_admin:
                dit = {
                    "user_id": db_obj.id,
                    "role_id": admin_id
                }
                db_obj = UserRole(**dit)   # type: ignore
                db.add(db_obj)
                db.commit()
                db.refresh(db_obj)











